package com.coocaa.framework.global;

import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedaemon.LiteDaemon;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;

import java.util.List;

/**
 * Created by luwei on 15-6-11.
 */
public class GlobalController extends LiteDaemon implements CoocaaApplication.PackageReceiver.InstallUninstallInterface {

    private static LiteDaemonInfo info = null;

    static {
        info = new LiteDaemonInfo();
        info.id = "com.coocaa.framework.global.GlobalController";
        info.name = "GlobalController";
    }

    public GlobalController() {
        super(info);
    }

    @Override
    public void installEvent(final Intent i) {
        post(new Runnable() {
            @Override
            public void run() {
                try {
                    List<DownloadTask> tasks = XServiceManager.getDownloaderService().getTaskList();
                    if (tasks != null && tasks.size() > 0) {
                        for (DownloadTask task : tasks) {
                            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
                            if (extra != null && extra.pkgname.equals(i.getData().getSchemeSpecificPart())) {
                                XServiceManager.getDownloaderService().delete(task);
                            }
                        }
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void uninstallEvent(final Intent i) {

    }

    @Override
    protected void onCreate(Context context) {
        CoocaaApplication.addPackageListener(this);
    }

    @Override
    protected void onDestroy() {
        CoocaaApplication.removePackageListener(this);
    }


}
